package handler

import (
	"gin-products/api/request"
	"gin-products/global"
	"gin-products/inter/dao"
	"gin-products/inter/model"
	"github.com/gin-gonic/gin"
	"net/http"
)

func AddOrder(c *gin.Context) {
	var req request.AddOrderReq
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 1000,
			"msg":  "验证失败",
			"data": nil,
		})
		return
	}
	var order model.Order
	var pro model.Product
	dao.GetOneByFields(&model.Product{
		Id: req.ProductId,
	}, &pro)
	if pro.Id == 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": 1000,
			"msg":  "商品不存在，无法下单",
			"data": nil,
		})
		return
	}
	order = model.Order{

		UserId:      req.UserId,
		ProductId:   req.ProductId,
		PayType:     req.PayType,
		OrderStatus: req.OrderStatus,
	}
	if !dao.Create(&order) {
		c.JSON(http.StatusOK, gin.H{
			"code": 1000,
			"msg":  "订单创建失败",
			"data": nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "订单创建成功",
		"data": order,
	})
}

func UpdateOrder(c *gin.Context) {
	var req request.UpdateOrderReq
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 1000,
			"msg":  "验证失败",
			"data": nil,
		})
		return
	}
	var order model.Order
	dao.GetOneByFields(&model.Order{
		Id: req.Id,
	}, &order)
	if order.Id == 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": 1000,
			"msg":  "订单不存在",
			"data": nil,
		})
		return
	}
	order = model.Order{
		Id: req.Id,

		OrderStatus: req.OrderStatus,
	}
	if !dao.Update(&order) {
		c.JSON(http.StatusOK, gin.H{
			"code": 1000,
			"msg":  "订单修改状态失败",
			"data": nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "订单修改状态成功",
		"data": order,
	})
}

func DelOrder(c *gin.Context) {
	var req request.DelOrderReq
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 1000,
			"msg":  "验证失败",
			"data": nil,
		})
		return
	}
	var order model.Order
	dao.GetOneByFields(&model.Order{
		Id: req.Id,
	}, &order)
	if order.Id == 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": 1000,
			"msg":  "订单不存在",
			"data": nil,
		})
		return
	}
	order = model.Order{
		Id: req.Id,
	}
	if !dao.Delete(&order) {
		c.JSON(http.StatusOK, gin.H{
			"code": 1000,
			"msg":  "订单删除失败",
			"data": false,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "订单删除成功",
		"data": true,
	})
}

func GetOrder(c *gin.Context) {
	var req request.GetOrderReq
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 1000,
			"msg":  "验证失败",
			"data": nil,
		})
		return
	}
	var order []*model.Order
	global.DB.Where("user_id = ?", req.UserId).Find(order)
	c.JSON(http.StatusOK, gin.H{
		"code": 1000,
		"msg":  "验证失败",
		"data": order,
	})
}
